package com.exception;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

/**
 * 不必在Controller中对异常进行处理，抛出即可，由此异常解析器统一控制。<br>
 * ajax请求（有@ResponseBody的Controller）发生错误，输出JSON。<br>
 * 页面请求（无@ResponseBody的Controller）发生错误，输出错误页面。<br>
 * @author microxdd
 * */
public class AnnotationHandlerMethodExceptionResolver implements HandlerExceptionResolver{
    private String defaultErrorView = "error.jsp";

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
	    HttpServletResponse response, Object handler, Exception ex) {
	// TODO Auto-generated method stub
	System.out.println("============exception================");
	ModelAndView mav = new ModelAndView();
	response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
	System.out.println(handler);
	if (handler != null) {
	    HandlerMethod handlerMethod = (HandlerMethod) handler;
	    Method method = handlerMethod.getMethod();
	    System.out.println("method:"+method);
	    ex.printStackTrace();
	    if (method != null) {
		ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(
			method, ResponseBody.class);
		if (responseBodyAnn != null) {
		    MappingJacksonJsonView view = new MappingJacksonJsonView();
		    Map<String, Object> attributes = new HashMap<String, Object>();
		    attributes.put("success", Boolean.FALSE);
		    attributes.put("msg", ex.toString());
		    view.setAttributesMap(attributes);
		    mav.setView(view);
		    //mav.addObject(attributes);
		    System.out.println("============exception================");
		    return mav;
		}
	    }
	}
	mav.setViewName(defaultErrorView);
	mav.addObject("ex", ex);
	return mav;
    }

    public String getDefaultErrorView() {
	return defaultErrorView;
    }

    public void setDefaultErrorView(String defaultErrorView) {
	this.defaultErrorView = defaultErrorView;
    }
}